﻿using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Sudum
{
#if SHOW_PERFORMANCE
	class PerformanceCounter : IDisposable
	{
		double qpcFrequencyMS;
		long startSampleTime;
		double lastDurationMS;
		SpriteBatch textRenderer;

		[DllImport("Kernel32")]
		private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

		[DllImport("Kernel32")]
		private static extern bool QueryPerformanceFrequency(out long lpFrequency);

		public PerformanceCounter()
		{
			long frequency = 1;
			QueryPerformanceFrequency(out frequency);
			qpcFrequencyMS = (double)frequency / 1000.0;
			textRenderer = new SpriteBatch(Sudum.Me.GraphicsDevice);
		}

		public void Dispose()
		{
			textRenderer.Dispose();
		}

		public void Draw()
		{
			Vector2 vPos = new Vector2(10f, 10f);
			string text = "CPU: " + lastDurationMS.ToString("F") + " ms";
			textRenderer.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);

			// Drop shadow
			textRenderer.DrawString(Sudum.Me.DebugTextFont, text, vPos + new Vector2(1, 0), Color.Black);
			textRenderer.DrawString(Sudum.Me.DebugTextFont, text, vPos + new Vector2(0, 1), Color.Black);

			// Draw value in proper color depending on whether time is within allowed limit or not
			textRenderer.DrawString(Sudum.Me.DebugTextFont, text, vPos, (lastDurationMS > 16.65) ? Color.Red : Color.LimeGreen);

			textRenderer.End();
		}

		public void Start()
		{
			QueryPerformanceCounter(out startSampleTime);
		}

		public void End()
		{
			long endSampleTime = startSampleTime;
			QueryPerformanceCounter(out endSampleTime);
			lastDurationMS = ((double)(endSampleTime - startSampleTime)) / qpcFrequencyMS;
		}
	}
#endif // SHOW_PERFORMANCE
}